package shiro;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;

/**
 * @author zhuqiang
 * @version V1.0
 * @date 2015/11/11 20:40
 */
public class HelloShiro {
    public static void main(String[] args) {
        //初始化 securityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager sm = factory.getInstance();
        SecurityUtils.setSecurityManager(sm); //给这个工具类设置 securityManager，以后使用这个工具类的时候，就等于在操作securityManager相关的数据了

        Subject subject = SecurityUtils.getSubject(); //获取当前用户（其实是获取到整个配置文件里面所有的用户信息）
        UsernamePasswordToken token = new UsernamePasswordToken("shiro", "1234"); //登录信息
        try {
            subject.login(token);  //使用登录信息和数据源中的信息比对（his.securityManager.login(this, token);）
        }catch (AuthenticationException e){
            System.out.println("登录失败:" + e);
            return;
        }
        System.out.println("登录成功:" + subject.getPrincipal());
        subject.logout();



        JdbcRealm jdbcRealm = new JdbcRealm();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/study?useUnicode=true&amp;characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123");
        jdbcRealm.setDataSource(dataSource); //设置数据源信息
        jdbcRealm.setAuthenticationQuery("SELECT `password` FROM `user` WHERE username = ?"); //设置查用户的认证信息

        //设置这个验证用户的权限名称
        jdbcRealm.setUserRolesQuery("SELECT r.role_name FROM `user` u,user_role ur,role r WHERE u.id = ur.user_id AND ur.role_id = r.id AND u.username=?");
        jdbcRealm.setPermissionsQuery("SELECT p.permission_name FROM role r,role_permission rp,permission p WHERE r.id = rp.role_id AND rp.permission_id = p.permission_name AND r.role_name = ?");
        jdbcRealm.setPermissionsLookupEnabled(true);

        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(jdbcRealm);
        PasswordMatcher passwordMatcher = new PasswordMatcher();
        MemoryConstrainedCacheManager memoryConstrainedCacheManager = new MemoryConstrainedCacheManager();
        DefaultPasswordService defaultPasswordService = new DefaultPasswordService();
        String encryptPassword = defaultPasswordService.encryptPassword("123");
    }
}
